package com.sk.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.sk.constant.DynamicSourceConstant;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;

/**
 * 数据源信息配置类
 * ,读取数据源信息，并注册为bean
 * @Author jiaok
 * @Date 2023-12-12 10:14
 */
@Configuration
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class })
public class DruidConfig {

    /**
     * ConfigurationProperties 不允许使用驼峰，要求全部小写
     * @return
     */
    @Bean(name = DynamicSourceConstant.BASEDB)
    @ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.basedb")
    public DataSource baseDbDataSource(){
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return dataSource;
    }

    @Bean
    @Primary
    public DynamicDataSourceConfig dynamicDataSourceConfig(){

        HashMap<Object, Object> dataSourceMap = new HashMap<>(16);
        dataSourceMap.put(DynamicSourceConstant.BASEDB,baseDbDataSource());

        //设置动态数据源解析
        DynamicDataSourceConfig dynamicDataSourceConfig = new DynamicDataSourceConfig();
        //设置数据源集
        dynamicDataSourceConfig.setTargetDataSources(dataSourceMap);
        dynamicDataSourceConfig.setDefaultTargetDataSource(baseDbDataSource());
        //将数据源信息进行备份
        dynamicDataSourceConfig.setDefineTargetDataSources(dataSourceMap);

        return dynamicDataSourceConfig;
    }

}
